package com.example.service.impl;

import com.example.dto.AssignRoleDto;
import com.example.entity.Result;
import com.example.entity.Role;
import com.example.mapper.RoleAuthMapper;
import com.example.mapper.RoleMapper;
import com.example.mapper.UserRoleMapper;
import com.example.page.Page;
import com.example.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author:tjf
 * @Description:
 */
@CacheConfig(cacheNames = "com.example.service.impl.RoleServiceImpl")
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleAuthMapper roleAuthMapper;

    /**
     * 查询所有角色的业务方法
     * @return
     */
//    @Cacheable(value = "role", key = "'all:role'")
    @Cacheable(key = "'all:role'")
    @Override
    public List<Role> queryAllRoles() {
        return roleMapper.selectAllRoles();
    }

    /**
     * 根据userId查询已分配的角色业务
     * @param userId
     * @return
     */
    @Override
    public List<Role> queryRoleListByUserId(int userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
     * 根据userId分配角色业务方法
     * @param assignRoleDto
     * @return
     */
    @Override
    @Transactional
    public Result assignRoleByUserId(AssignRoleDto assignRoleDto) {
        List<String> roleCheckList = assignRoleDto.getRoleCheckList();
        Integer userId = assignRoleDto.getUserId();

        // 判断是否给userId分配了角色
        if (roleCheckList == null || roleCheckList.size() == 0){// 没有分配
            userRoleMapper.deleteUserRoleByUserId(userId);
            return Result.ok("用户分配角色成功！");
        }

        // 分配了角色
        // 根据roleName查询roleId
        List<Integer> roleIdList = roleMapper.selectRoleIdByRoleName(roleCheckList);

        // 根据userId删除UserRole记录
        userRoleMapper.deleteUserRoleByUserId(userId);

        // 根据roleIdList和userId新增UserRole记录
        userRoleMapper.insertUserRoleByBatch(roleIdList, userId);

        return Result.ok("用户分配角色成功！");
    }

    /**
     * 根据条件分页查询角色的业务方法
     * @param role
     * @param page
     * @return
     */
    @Override
    public Page queryRoleByConditionForPagination(Role role, Page page) {
        // 根据条件，查询总的记录条数
        int roleCount = roleMapper.selectRoleCountByConditionForPagination(role);

        // 根据条件，查询角色
        List<Role> roleList = roleMapper.selectRoleByConditionForPagination(role, page);

        // 封装参数page
        page.setResultList(roleList);
        page.setTotalNum(roleCount);

        // 返回结果page
        return page;
    }

    /**
     * 新增角色的业务方法
     * @param role
     * @return
     */
    @CacheEvict(key = "'all:role'")
    @Override
    public Result saveRole(Role role) {
        String roleName = role.getRoleName();
        // 根据roleName判断roleName是否存在
        if (roleMapper.selectRoleByRoleName(roleName) != null) {// roleName存在
            return Result.err(Result.CODE_ERR_BUSINESS, "角色名称已存在！");
        }

        String roleCode = role.getRoleCode();
        // 根据roleCode判断roleCode是否存在
        if (roleMapper.selectRoleByRoleCode(roleCode) != null){ // roleCode存在
            return Result.err(Result.CODE_ERR_BUSINESS, "角色代码已存在！");
        }

        // roleCode和roleName都不存在
        // 对role进行持久化
        if (roleMapper.insertRole(role) <= 0) {// 持久化失败
            return Result.err(Result.CODE_ERR_BUSINESS, "系统忙，请稍后重试！");
        }
        return Result.ok("角色添加成功！");
    }

    /**
     * 根据roleId修改roleState的业务方法
     * @param role
     * @return
     */
    @CacheEvict(key = "'all:role'")
    @Override
    public Result modifyRoleStateByRoleId(Role role) {
        if (roleMapper.updateRoleStateByRoleId(role) <= 0) {
            return Result.err(Result.CODE_ERR_BUSINESS, "系统忙，请稍后重试！");
        }
        return Result.ok();
    }

    /**
     * 根据roleId分配权限的业务方法
     * @param roleId
     * @param authIdList
     */
    @Transactional
    @Override
    public void grantAuthByRoleId(int roleId, List<Integer> authIdList) {
        // 根据roleId删除role_auth表中所有的authId
        roleAuthMapper.deleteRoleAuthByRoleId(roleId);

        // 给roleId分配authIdList中所有的权限
        roleAuthMapper.insertRoleAuthByRoleId(roleId, authIdList);
    }

    /**
     * 根据角色id删除角色的业务方法
     * @param roleId
     */
    @Transactional
    @Override
    public void removeRoleByRoleId(int roleId) {
        // 根据角色id把角色本身的权限删除
        roleAuthMapper.deleteRoleAuthByRoleId(roleId);

        // 再根据角色id删除角色
        roleMapper.deleteRoleByRoleId(roleId);
    }

    /**
     * 根据roleId修改role的描述的业务方法
     * @param role
     * @return
     */
    @Override
    public Result modifyRoleDescByRoleId(Role role) {
        // 根据roleId修改role的描述
        if (roleMapper.updateRoleDescByRoleId(role) <= 0) {// 系统出现问题
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }
        return Result.ok("角色信息修改成功！");
    }
}
